package util

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

func listFiles(path string) ([]string, error) {
	var files []string
	err := filepath.Walk(path, func(filePath string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			ext := strings.ToLower(filepath.Ext(filePath))
			if ext == ".jpg" || ext == ".png" { // 文件类型可以自己指定
				files = append(files, filePath)
			}
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return files, nil
}

func handle(dirPath string) {
	boundaryStr := "-----------------------------202208090741"
	boundaryBytes := []byte(fmt.Sprintf("\r\n--%s\r\n", boundaryStr))

	filePaths, err := listFiles(dirPath)
	if err != nil {
		log.Fatalf("Failed to list files: %v", err)
	}
	bodyWriter := &bytes.Buffer{}
	writer := multipart.NewWriter(bodyWriter)
	bodyWriter.Write(boundaryBytes)
	for _, file := range filePaths {
		fileWriter, err := writer.CreateFormFile("files[]", filepath.Base(file))
		if err != nil {
			log.Fatalf("Failed to create form file: %v", err)
		}
		fh, err := os.Open(file)
		if err != nil {
			log.Fatalf("Failed to open file: %v", err)
		}
		defer fh.Close()
		if _, err = io.Copy(fileWriter, fh); err != nil {
			log.Fatalf("Failed to copy file: %v", err)
		}
		bodyWriter.Write([]byte("\r\n"))
	}
	bodyWriter.Write(boundaryBytes)
	contentType := fmt.Sprintf("multipart/form-data; boundary=%s", boundaryStr)

	client := http.Client{Timeout: 10 * time.Second}
	req, err := http.NewRequest(http.MethodPost, "url", bodyWriter)
	if err != nil {
		log.Fatalf("Failed to create request: %v", err)
	}
	req.Header.Set("Content-Type", contentType)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("Failed to do request: %v", err)
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Failed to read response body: %v", err)
	}
	fmt.Printf("Response: %s\n", string(respBody))

}
